namespace('User.Error');
namespace('Group');
User.uid = 0;
User.Error.ERROR_WRONG_SESSION = 1;
User.Error.ERROR_WRONG_USER = 2;
User.Error.ERROR_NO_USER = 3;
User.Error.ERROR_NO_GROUP = 4;
User.Error.ERROR_WRONG_RIGHT = 5;
User.Error.ERROR_NO_MODULE = 6;
User.module = 'modules/administration/';
Group = User;
Group.gid = 0;

$(document).ready(rdy);
function rdy() {


    $("#user").autocomplete({
        source: function(query, add){
            $.getJSON(User.module+"userService.php", query, function(data) {
                var suggestions = [];
                $.each(data, function(i,val) {
                    suggestions.push(val);
                });
                add(suggestions);
            });
        } ,
        minLength: 3,
        
        select:
        function(e, ui) {
            $("#uid").val(ui.item.uid);
            $("#details").val(ui.item.value);
        }
    });
    
    $("#userRights").autocomplete({
        source: function(query, add){
            $.getJSON(User.module+"userService.php", query, function(data) {
                var suggestions = [];
                $.each(data, function(i,val) {
                    suggestions.push(val);
                });
                add(suggestions);
            });
        } ,
        minLength: 3,
        
        select:
        function(e, ui) {
            $(this).attr('disabled',true);
            User.uid = ui.item.uid;
            $.getJSON(User.module+'rightsService.php', {action: 'get', type: 'user', uid: User.uid}, showUserRights);
        }
    });
    
    $("#groupRights").autocomplete({
        source: function(query, add){
            $.getJSON(User.module+"groupService.php", query, function(data) {
                var suggestions = [];
                $.each(data, function(i,val) {
                    suggestions.push(val);
                });
                add(suggestions);
            });
        } ,
        minLength: 0,
        
        select:
        function(e, ui) {
            $(this).attr('disabled',true);
            Group.gid = ui.item.gid;
            $.getJSON(User.module+'rightsService.php', {action: 'get', type: 'group', gid: Group.gid}, showGroupRights);
        }
    });
    
    $("#other").click(function() {
        $('#userRights').attr('disabled',false);
        $('#userRights').val('');
        $('#userRightsInfo').css('display', 'none');
        $(this).attr('disabled',true);
        User.uid = 0;
    });
    
    $("#otherGroup").click(function() {
        $('#groupRights').attr('disabled',false);
        $('#groupRights').val('');
        $('#groupRightsInfo').css('display', 'none');
        $(this).attr('disabled',true);
        Group.gid = 0;
    });
}

function showUserRights(json) {
    $("#other").attr('disabled', false);
    $('#userRightsInfo').css('display', 'block');
    if(json.hasOwnProperty('error')) {
        showError(json.error, $('#userRightsInfo'));
    } else {
        var html = '<br />';
        User.uid = json.uid;
        if(json.gRights.length > 0) {
            html += '<table><thead><tr><th colspan="2">Prawa dziedziczone z grupy</th></tr><tr><th>Moduł</th><th>Poziom</th></tr></thead><tbody>';
            $.each(json.gRights, function(index, right) {
                html += '<tr><td>'+right.name+'</td><td>'+right.lvl+'</td></tr>';
            });
            html += '</tbody></table><br />';
        } else {
            html += '<span class="info">Użytkownik nie posiada żadnych praw dziedziczonych z grupy.</span><br />';
        }
        
        html += 'Zacznij pisać nazwę modułu, do którego chcesz nadać prawa dla użytkownika<br /><input type="text" id="module" /><br /><br />';
        html += '<table id="userRightsTable"><thead><tr><th colspan="3">Prawa użytkownika</th></tr><tr><th>Moduł</th><th>Poziom</th><th>Akcje</th></tr></thead><tbody>';
        if(json.rights.length > 0) {
            $.each(json.rights, function(index, right) {
                html += addTr('', right.name, right.mid, right.lvl, false, true);
            });
        }
        
        html += '</tbody></table><br /><br /><span class="info"' + (json.rights.length > 0 ? ' style="display: none;" ' : '') + 'id="noRights">Użytkownik nie posiada praw do żadnego z modułów.</span>';
        
        $('#userRightsInfo').html(html + '<br />');
        $('.setUserRight').click(setUserRight);
        $('.delUserRight').click(delUserRight);
        $("#module").autocomplete({
            source: function(query, add){
                query.uid = User.uid;
                $.getJSON(User.module+"moduleService.php", query, function(data) {
                    var suggestions = [];
                    $.each(data, function(i,val) {
                        suggestions.push(val);
                    });
                    add(suggestions);
                });
            } ,
            minLength: 0,

            select: addUserRight
        });
    }
}

function showGroupRights(json) {
    $("#otherGroup").attr('disabled', false);
    $('#groupRightsInfo').css('display', 'block');
    if(json.hasOwnProperty('error')) {
        showError(json.error, $('#groupRightsInfo'));
    } else {
        var html = '<br />';
        Group.gid = json.gid;
        
        html += 'Zacznij pisać nazwę modułu, do którego chcesz nadać prawa dla grupy<br /><input type="text" id="module" /><br /><br />';
        html += '<table id="groupRightsTable"><thead><tr><th colspan="3">Prawa grupy</th></tr><tr><th>Moduł</th><th>Poziom</th><th>Akcje</th></tr></thead><tbody>';
        if(json.rights.length > 0) {
            $.each(json.rights, function(index, right) {
                html += addTr('', right.name, right.mid, right.lvl, false, false);
            });
        }
        
        html += '</tbody></table><br /><br /><span class="info"' + (json.rights.length > 0 ? ' style="display: none;" ' : '') + 'id="noRights">Grupa nie posiada praw do żadnego z modułów.</span>';
        
        $('#groupRightsInfo').html(html + '<br />');
        $('.setGroupRight').click(setGroupRight);
        $('.delGroupRight').click(delGroupRight);
        $("#module").autocomplete({
            source: function(query, add){
                query.gid = Group.gid;
                $.getJSON(User.module+"moduleService.php", query, function(data) {
                    var suggestions = [];
                    $.each(data, function(i,val) {
                        suggestions.push(val);
                    });
                    add(suggestions);
                });
            } ,
            minLength: 0,

            select: addGroupRight
        });
    }   
}

function showError(errorCode, where) {
    where.attr('display','block');
    switch(errorCode) {
        case User.Error.ERROR_WRONG_SESSION:
            where.val('<span class="error">Twoja sesja wygasła! Aby móc zarządzać prawami dostępu do modułów musisz się przelogować.</span>');
        break;
        case User.Error.ERROR_WRONG_USER:
        break;
        case User.Error.ERROR_NO_USER:
        break;
        case User.Error.ERROR_NO_GROUP:
        break;
        case User.Error.ERROR_WRONG_RIGHT:
        break;
        default:
        break;
    }
}

function setUserRight() {
    var mid = $(this).attr('id').split('_')[1];
    var lvl = $('#'+mid).val();
    lvl = parseInt(lvl);
    $.getJSON(User.module+'rightsService.php', {action: 'set', type: 'user', uid: User.uid, mid: mid, lvl: lvl}, setRightCallback);
}

function delUserRight() {
    var mid = $(this).attr('id').split('_')[1];
    $.getJSON(User.module+'rightsService.php', {action: 'del', type: 'user', uid: User.uid, mid: mid}, delRightCallback);
}

function addUserRight(e, u) {
    $('#noRights').hide();
    $.getJSON(User.module+'rightsService.php', {action: 'set', type: 'user', uid: User.uid, mid: u.item.mid, lvl: 0}, addUserRightCallback);
}

function addUserRightCallback(json) {
    if(json.error > 0) {
        showError(json.error,$('#actions'));
    } else {
        var elem = $('#actions');
        elem.css('display','block');
        elem.text('Prawo do modułu zostało dodane.');
        addTr('userRightsTable',json.name,json.mid,json.lvl,true, true);
    }
    setTimeout(function() {$('#actions').hide('fast');}, 3000);
    $('#module').val('');
}

function setGroupRight() {
    var mid = $(this).attr('id').split('_')[1];
    var lvl = $('#'+mid).val();
    lvl = parseInt(lvl);
    $.getJSON(User.module+'rightsService.php', {action: 'set', type: 'group', gid: Group.gid, mid: mid, lvl: lvl}, setRightCallback);
}

function delGroupRight() {
    var mid = $(this).attr('id').split('_')[1];
    $.getJSON(User.module+'rightsService.php', {action: 'del', type: 'group', gid: Group.gid, mid: mid}, delRightCallback);
}

function addGroupRight(e, u) {
    $('#noRights').hide();
    $.getJSON(User.module+'rightsService.php', {action: 'set', type: 'group', gid: Group.gid, mid: u.item.mid, lvl: 0}, addGroupRightCallback);
}

function addGroupRightCallback(json) {
    if(json.error > 0) {
        showError(json.error,$('#actions'));
    } else {
        var elem = $('#actions');
        elem.css('display','block');
        elem.text('Prawo do modułu zostało dodane.');
        addTr('groupRightsTable',json.name,json.mid,json.lvl,true, false);
    }
    setTimeout(function() {$('#actions').hide('fast');}, 3000);
    $('#module').val('');
}

function delRightCallback(json) {
    if(json.error > 0) {
        showError(json.error,$('#actions'));
    } else {
        var elem = $('#actions');
        elem.css('display','block');
        elem.text('Prawo do modułu zostało usunięte.');
        crossOutTr('tr_'+json.mid);
    }
    setTimeout(function() {$('#actions').hide('fast');}, 3000);
}

function setRightCallback(json) {
    if(json.error > 0) {
        showError(json.error,$('#actions'));
    } else {
        var elem = $('#actions');
        elem.css('display','block');
        elem.text('Prawo do modułu zostało zmienione.');
    }
    setTimeout(function() {$('#actions').hide('fast');}, 3000);
}

function crossOutTr(trId) {
    $('#'+trId).children('td').css('text-decoration','line-through');
    $('#'+trId).children('td').children('input').css('text-decoration','line-through');
    $('#'+trId).children('td').children('input').attr('disabled', true);
    $('#'+trId).fadeOut(2000);
    setTimeout(function() {
        $('#'+trId).remove();
        if($('#userRightsTable').find('tbody').find('tr').length < 1 && $('#groupRightsTable').find('tbody').find('tr').length < 1) {
            $('#noRights').show();
        }
    },2000);
}

function addTr(tableId, moduleName, mid, lvl, ready, user) {
    if(ready) {
        var table = $('#'+tableId);
        table = table.children('tbody');
        table.append('<tr id="tr_'+mid+'"><td>'+moduleName+'</td><td><input type="text" id="'+mid+'" value="'+lvl+'" class="rightLvl" /></td><td><input type="button" id="s_'+mid+'" class="setUserRight setGroupRight" value="Zmień" /><input type="button" id="d_'+mid+'" class="delUserRight delGroupRight" value="Usuń" /></td></tr>');
        if(user) {
            $('.setUserRight').unbind('click');
            $('.delUserRight').unbind('click');
            $('.setUserRight').click(setUserRight);
            $('.delUserRight').click(delUserRight);
        } else {
            $('.setGroupRight').unbind('click');
            $('.delGroupRight').unbind('click');
            $('.setGroupRight').click(setGroupRight);
            $('.delGroupRight').click(delGroupRight);
        }
    } else {
        return '<tr id="tr_'+mid+'"><td>'+moduleName+'</td><td><input type="text" id="'+mid+'" value="'+lvl+'" class="rightLvl" /></td><td><input type="button" id="s_'+mid+'" class="setUserRight setGroupRight" value="Zmień" /><input type="button" id="d_'+mid+'" class="delUserRight delGroupRight" value="Usuń" /></td></tr>';
    }
}